
package com.scalar.chiptrack.operations.packingslip.actions;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.externalusers.dao.ExternalUserSetupDAO;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLineItems;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLotNumberData;
import com.scalar.chiptrack.operations.packingslip.FinalInventoryData;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.operations.packingslip.forms.SendMailForm;
import com.scalar.chiptrack.operations.packingslip.forms.ShippingAdviseForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;


public final class ShippingAdviseAction extends ChipTrackAction
{
    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response )
        throws Exception
    {


        HashMap<String, String> errors = new HashMap<String, String>();
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        HashMap<String, String> info = new HashMap<String, String>();
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );

        String action = request.getParameter( "action" );
        String cstKeyParameter = request.getParameter ( "cstKey" );
        String psParameter = request.getParameter( "ps" );
        HashMap finalInventoryMap = null;

        int cstRandomKey = -1;

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute ( SessionKeys.USER_KEY );
        if( user == null )
        {
            session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, request.getServletPath() + "?" + request.getQueryString() );
            return( mapping.findForward( SessionKeys.ACTION_FORWARD_KEY_LOGIN ) );
        }

        if ( !user.isActionAllowed( Functionality.PACKING_SLIP, User.USER_ACTION_VIEW ) )
        {
            return (mapping.findForward ("failure"));
        }
        
		//int customerShippingId = -1;
		//customerShippingId  = Integer.parseInt( request.getParameter("ps") );
        if( psParameter != null && !"null".equalsIgnoreCase(psParameter) )
        {   
            int customerShippingId = -1;
            try
            {
                customerShippingId  = Integer.parseInt( request.getParameter("ps") );
            } catch(NumberFormatException e){}
            int packingSlipVendorId = ExternalUserSetupDAO.getPackingSlipVendorId( null, customerShippingId );
            if( user.getVendorId() != packingSlipVendorId )
            {
                errors.put ( "User not associated with this Packing Slip", null );
                request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                return (mapping.findForward ("failure"));
            }
        }

        if ( action == null )
        {
            session.setAttribute( "ps" , psParameter );
            session.setAttribute( "cstKey" , cstKeyParameter );
            if( cstKeyParameter != null && ( cstKeyParameter.trim().length() > 0 ) ) {
               try {
                    cstRandomKey = Integer.parseInt( cstKeyParameter );
                }
                catch( NumberFormatException nfe ) {
                    System.out.println( "Random ID passed is not an integer: " + cstRandomKey );
                }
            }
        }
		
        ShippingAdviseForm shippingAdviseForm = ( ShippingAdviseForm ) form;

        if( ( action == null ) || ( action.equalsIgnoreCase( "view" ) == true ) || ( action.equalsIgnoreCase( "editback" ) == true ))
        {

            if ( "editback".equalsIgnoreCase(action) )
            {
                shippingAdviseForm.setConfrimPackingSlip( false );
                request.setAttribute("editback", "true");
                request.setAttribute( "weightMeasurementList", NewPackingSlipDAO.loadWeightMeasurements() );
				request.setAttribute( "uomPgkDimensionList", NewPackingSlipDAO.loadUomPkgDimensionList() );
                return mapping.findForward( "success" );
            }
            if ( shippingAdviseForm.isConfrimPackingSlip() )
            {
                ClientInfo clientInfo = UserDAO.getClientAddressInfo();
                // this particular code needs to be changed
                // we need to use the same finalInventoryMap we had in session
                if( session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) != null)
                {
                    HashMap InventoryDataMapDB          = NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( shippingAdviseForm.getCustomerShippingId() ) ;
                    HashMap existingInventoryDataMap    = getFinalInventoryMapByCustomerShippingId ( (HashMap) session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) );
                    shippingAdviseForm.setFinalInventoryDataMap( getFinalInventoryMapByCustomerShippingId( (HashMap)session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) ) );
                    shippingAdviseForm.setFinalInventoryDataMapView( loadNewFinalInventoryDataListMap ( existingInventoryDataMap , InventoryDataMapDB ) );
                }
                else
                {
                    shippingAdviseForm.setFinalInventoryDataMap( NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( shippingAdviseForm.getCustomerShippingId() ) );
                    shippingAdviseForm.setFinalInventoryDataMapView( shippingAdviseForm.getFinalInventoryDataMap() );
                }

                request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );
                shippingAdviseForm.setClientInfo( clientInfo );
                shippingAdviseForm.setShippingVendorAddressObject( VendorDAO.getVendorNameAndAddress(shippingAdviseForm.getShippingFromLocationId()));
                return( mapping.findForward( "shippingAdviseView" ) );

            }


            session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
		    session.removeAttribute( "repetedPartNumber" );

            int cstShipId = -1;
            int packingslipID = -1;
            try
            {
                packingslipID = Integer.parseInt( psParameter );
            }
            catch( NumberFormatException nfe )
            {
                System.out.println( "Packingslip ID passed is not an integer: " + psParameter );
                //nfe.printStackTrace();
            }
            try
            {
                if( packingslipID != -1 )
                {
                    shippingAdviseForm.setExternalUserId( user.getUserId() );
                    if ( cstRandomKey != -1 && cstRandomKey != 0 )
                    {
                        cstShipId = NewPackingSlipDAO.getCstShippingIdByRandomKey(cstRandomKey);
                        if ( cstShipId != -1 )
                        {
                            shippingAdviseForm = NewPackingSlipDAO.loadShippingAdviceById( cstShipId, user );
                        }
                    }
                    else if ( cstRandomKey == 0 )
                    {
                        shippingAdviseForm = NewPackingSlipDAO.loadShippingAdviceById( packingslipID, user );
                    }

                    ArrayList repetedPartNumber = new ArrayList();
                    if ( shippingAdviseForm.getLineitems() != null && shippingAdviseForm.getLineitems().size() > 0 )
                    {
                        repetedPartNumber = NewPackingSlipDAO.getRepetedPartNumbers ( shippingAdviseForm.getLineitems() );
                        if( repetedPartNumber.size() > 0 )
                        {
                            session.setAttribute( "repetedPartNumber", repetedPartNumber );
                        }
                    }
                    if( shippingAdviseForm == null )
                    {
                        errors.put( "No details found in the system for this Packingslip", null );
                    }
                    if( shippingAdviseForm.getCustomerShippingId() == -1 )
                    {
                        errors.put( "No details found in the system for this Packingslip", null );
                    }
                }
            }
            catch (ScalarException se)
            {
                errors.put ("Internal Server Error", "Could not retreive Information");
            }
        }
        else if( "updateinfo".equalsIgnoreCase( action ) == true )
        {
            try
            {
                if( shippingAdviseForm.getCustomerShippingId() != -1 )
                {
                    if( session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) != null)
                    {
                        finalInventoryMap = (HashMap) session.getAttribute ( SessionKeys.FINAL_INVENTORY_MAP );
                    }

                    NewPackingSlipDAO.updateShippingAdvise( null, shippingAdviseForm, finalInventoryMap );

                    session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
					session.removeAttribute( "repetedPartNumber" );

                    shippingAdviseForm = NewPackingSlipDAO.loadShippingAdviceById( shippingAdviseForm.getCustomerShippingId(), user );
                    ArrayList repetedPartNumber = new ArrayList();
                    if ( shippingAdviseForm.getLineitems() != null && shippingAdviseForm.getLineitems().size() > 0 )
                    {
                        repetedPartNumber = NewPackingSlipDAO.getRepetedPartNumbers ( shippingAdviseForm.getLineitems() );
                        if( repetedPartNumber.size() > 0 )
                        {
                            session.setAttribute( "repetedPartNumber", repetedPartNumber );
                        }
                    }

                    /*try
                    {
                        String[] clientShipAlertEmails = NewPackingSlipDAO.loadClientEmailsForShipAlert();
                        String[] allShipAlertEmails    = NewPackingSlipDAO.loadAllShipAlertEmails( shippingAdviseForm.getCustomerShippingId() );
                        SendMailForm sendMailForm = new SendMailForm();
                        sendMailForm.setFromUser( ConfigManager.getPackingSlipFromMailId() );
                        sendMailForm.setRecipientType("customer");//setting to customer beacause pdf attachment shoule be of ps type
                        sendMailForm.setAttachMIMEType( "PDF" );
                        sendMailForm.setSendCommercialInvoice( "on" );
                        sendMailForm.setSubject( "Shipment Notification - " + shippingAdviseForm.getNumber() + ", " + new Date( System.currentTimeMillis() ) );
                        if( clientShipAlertEmails != null && clientShipAlertEmails.length > 0 )
                        {
                            sendMailForm.setToUsers( clientShipAlertEmails );
                        }
                        else if ( ( clientShipAlertEmails == null || clientShipAlertEmails.length == 0 ) && allShipAlertEmails != null && allShipAlertEmails.length > 0   )
                        {
                            sendMailForm.setToUsers( allShipAlertEmails );
                        }
                        sendMailForm.setCcUsers( allShipAlertEmails );

                        request.setAttribute( "customerShippingId", shippingAdviseForm.getCustomerShippingId()+"" );
                        request.setAttribute( "action", "save" );
                        request.setAttribute( "isFromTrackingNoPage", "true" );
                        request.setAttribute( "shipAlertMessage", getShipAlertMessageBody( request.getHeader( "HOST" ), shippingAdviseForm ) );
                        new SendMailAction().execute( mapping, sendMailForm, request, response );
                        mailSuccess = true;

                        HashMap sendMailInfo = ( HashMap ) request.getAttribute( SessionKeys.INFO_MESSAGES) ;
                        HashMap sendMailError = ( HashMap ) request.getAttribute( SessionKeys.ERROR_MESSAGES) ;
                        if( sendMailInfo.containsKey( "Packingslip and Commercial Invoices have been sent, successfully" ) )
                        {
                            mailSuccess = true;
                            sendMailInfo.remove( "Packingslip and Commercial Invoices have been sent, successfully" );
                            sendMailInfo.put ( "Information has been updated successfully and also sent mail", null );
                        }
                        else
                        {
                            mailSuccess = false;
                            sendMailError.remove("Sending Failed ");
                            sendMailInfo.put ( "Information has been updated successfully and could not send mail", null );
                        }
                    }
                    catch ( Exception e )
                    {
                        e.printStackTrace();
                        mailSuccess = false;
                    }*/

                    shippingAdviseForm.setShowSendShipAlertLink( "true" );
                    info.put( "Information has been updated successfully", null );
                }
            }
            catch( Throwable t )
            {
                t.printStackTrace();
                errors.put( "Exception while updating the information", t.getMessage() );
            }
        }
        else if( action.equalsIgnoreCase( "confirmVendorPackingSlip" ) )
		{
            int customerShippingId = shippingAdviseForm.getCustomerShippingId();
            if ( Constants.CUSTOMER_SHIPPING_STATUS_SHIPPED.equalsIgnoreCase( NewPackingSlipDAO.getPackingSlipStatus( null, customerShippingId) ) )
            {
                errors.put ( "PackingSlip (" + shippingAdviseForm.getNumber() + ") is already confirmed", null );
                try
                {
                    shippingAdviseForm = null;
                    shippingAdviseForm = NewPackingSlipDAO.loadShippingAdviceById( customerShippingId, user );
                    session.setAttribute( "shippingAdviseForm", shippingAdviseForm );
                }
                catch ( ScalarException se )
                {
                    errors.put ("Internal Server Error", "Could not load Packing Slip");
                    errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
                    session.setAttribute( SessionKeys.ERROR_REPORT, se );
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                }
                shippingAdviseForm.setShowSendShipAlertLink( "true" );
                request.setAttribute( "weightMeasurementList", NewPackingSlipDAO.loadWeightMeasurements() );
                request.setAttribute( "uomPgkDimensionList", NewPackingSlipDAO.loadUomPkgDimensionList() );
                request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
                return mapping.findForward( "success" );
            }
            boolean mailSuccess = false;
            shippingAdviseForm.setConfrimPackingSlip( false );
            try
            {
                if( shippingAdviseForm.getCustomerShippingId() != -1 )
                {
                    if( session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) != null)
                    {
                        finalInventoryMap = (HashMap) session.getAttribute ( SessionKeys.FINAL_INVENTORY_MAP );
                        HashMap inventoryDataMapDB = NewPackingSlipDAO.getFinalInventoryMapByLineItemId( NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId ( shippingAdviseForm.getCustomerShippingId() ) );
                        loadNewFinalInventoryDataListMap( finalInventoryMap, inventoryDataMapDB );
                    }
                    else
                    {
                        finalInventoryMap = NewPackingSlipDAO.loadLotNumberAndLineItemDataByCSID ( shippingAdviseForm.getCustomerShippingId() );
                    }
                    NewPackingSlipDAO.confirmShippingAdvise ( shippingAdviseForm, finalInventoryMap, user.getFirstName() );
                }
            }
            catch ( ScalarException se )
            {
                se.printStackTrace();
                errors.put ( "Internal Server Error", "Could not confirm packingslip (" + shippingAdviseForm.getNumber() + ")" );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not confirm packingslip (" + shippingAdviseForm.getNumber() + ")" );
                session.setAttribute( SessionKeys.ERROR_REPORT, se );
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            }
            try
			{
                shippingAdviseForm = null;
                shippingAdviseForm = NewPackingSlipDAO.loadShippingAdviceById( customerShippingId, user );
                session.setAttribute( "shippingAdviseForm", shippingAdviseForm );
            }
			catch ( ScalarException se )
			{
				errors.put ("Internal Server Error", "Could not load Packing Slip");
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
				session.setAttribute( SessionKeys.ERROR_REPORT, se );
				request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
			}

            try
            {
                if ( ConfigManager.isSendShipmentNotificationMail() )
                {
                    if( shippingAdviseForm.getCustomerNumber().equalsIgnoreCase( shippingAdviseForm.getVendorName() ) ) //SHIPPING FROM THE CUSTOMER CONSIGNMENT WAAREHOUSE TO THE CUSTOMER
                    {
                        if ( ConfigManager.isSendShipmentNotificationWhenPulledFromConsignmentWareHouse() )
                        {
                            mailSuccess = sendShipmentNotificationMail( mapping, request, response, getShipAlertMessageBody( request.getHeader( "HOST" ), shippingAdviseForm ), shippingAdviseForm.getCustomerShippingId(), shippingAdviseForm.getNumber() );
                            if ( mailSuccess )
                            {
                                info.put( "Email notification sent successfully", null );
                            }
                            else
                            {
                                errors.put ( "Could not send email notification", null );
                            }
                        }
                    }
                    else
                    {
                        mailSuccess = sendShipmentNotificationMail( mapping, request, response, getShipAlertMessageBody( request.getHeader( "HOST" ), shippingAdviseForm ), shippingAdviseForm.getCustomerShippingId(), shippingAdviseForm.getNumber() );
                        if ( mailSuccess )
                        {
                            info.put( "Email notification sent successfully", null );
                        }
                        else
                        {
                            errors.put ( "Could not send email notification", null );
                        }
                    }
                }
            }
            catch ( Exception e )
            {
                e.printStackTrace();
                mailSuccess = false;
                errors.put ( "Could not send email notification", null );
            }
            shippingAdviseForm.setShowSendShipAlertLink( "true" );
            info.put ( "PackingSlip (" + shippingAdviseForm.getNumber() + ") has been confirmed(Invoice #: " + shippingAdviseForm.getInvoiceNumber() + ")", null );
			request.setAttribute( "weightMeasurementList", NewPackingSlipDAO.loadWeightMeasurements() );
			request.setAttribute( "uomPgkDimensionList", NewPackingSlipDAO.loadUomPkgDimensionList() );
            request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
            return mapping.findForward( "success" );
		}
        else if( "notify".equalsIgnoreCase( action ) == true )
        {
            try
            {
                // Step 1
                // Load "To" and "CC" Emails from Database
                String tempPSPdfUrl = null;
                String tempCSPdfUrl = null;
                String[] clientShipAlertEmails = NewPackingSlipDAO.loadClientEmailsForShipAlert();
                String[] customerEmails = NewPackingSlipDAO.loadCustomerShipAlertEmails( shippingAdviseForm.getCustomerName() );

                //System.out.println(" client emails = " + clientShipAlertEmails );

                // Step 2
                // Construct and populate the sendMailForm
                SendMailForm sendMailForm = new SendMailForm();
                sendMailForm.setAttachMIMEType( "HTML" );
                sendMailForm.setSendCommercialInvoice( null );
                sendMailForm.setSubject( "Shipment Notification - " + shippingAdviseForm.getNumber() + ", " + new Date( System.currentTimeMillis() ) );
                sendMailForm.setToUsers( clientShipAlertEmails );
                sendMailForm.setCcUsers( customerEmails );

                // Step 3
                // Call SendMailAction
                request.setAttribute( "customerShippingId", shippingAdviseForm.getCustomerShippingId()+"" );
                request.setAttribute( "action", "save" );
                request.setAttribute( "isFromTrackingNoPage", "true" );

                tempPSPdfUrl = shippingAdviseForm.getGeneratedPackingSlipPdfURL();
                tempCSPdfUrl = shippingAdviseForm.getGeneratedCommercialInvoicePdfURL();

                shippingAdviseForm = NewPackingSlipDAO.loadShippingAdviceById( shippingAdviseForm.getCustomerShippingId(), user );
                session.removeAttribute( "repetedPartNumber" );
                ArrayList repetedPartNumber = new ArrayList();
                if ( shippingAdviseForm.getLineitems() != null && shippingAdviseForm.getLineitems().size() > 0 )
                {
                    repetedPartNumber = NewPackingSlipDAO.getRepetedPartNumbers ( shippingAdviseForm.getLineitems() );
                    if( repetedPartNumber.size() > 0 )
                    {
                        session.setAttribute( "repetedPartNumber", repetedPartNumber );
                    }
                }
                shippingAdviseForm.setGeneratedPackingSlipPdfURL( tempPSPdfUrl );
                shippingAdviseForm.setGeneratedCommercialInvoicePdfURL( tempCSPdfUrl );
                shippingAdviseForm.setShowSendShipAlertLink( "true" );
                request.setAttribute( "shipAlertMessage", getShipAlertMessageBody( request.getHeader( "HOST" ), shippingAdviseForm ) );
                new SendMailAction().execute( mapping, sendMailForm, request, response );
            }
            catch( Throwable t )
            {
                t.printStackTrace();
                errors.put( "Internal Server Error", "Could not send the notification" );
            }
        }
        else if( "removeTracking".equalsIgnoreCase( action ) == true )
        {
            try
            {
                String cslitId = request.getParameter( "cslitId" );
                String lotId = request.getParameter( "lotId" );
                String lotNumber = request.getParameter( "lotNumber" );

                boolean updated = NewPackingSlipDAO.updateLotTrackingNumber( null, cslitId, lotId, null /* Tracking Number */ );

                // Load form again from DB
                shippingAdviseForm = NewPackingSlipDAO.loadShippingAdviceById( Integer.parseInt( request.getParameter( "ps" ) ), user );
                shippingAdviseForm.setShowSendShipAlertLink( "true" );

                if( updated == true )
                {
                    info.put( "Tracking Number has been removed for the Lot " + lotNumber, null );
                }
            }
            catch( Throwable t )
            {
                errors.put( "Internal Server Error", "Could not remove the tracking number" );
            }
        }
        else if( "generatePDF".equalsIgnoreCase( action ) == true )
        {
            try
            {
                String cstIdStr = request.getParameter("customerShippingId");
                String fileType = request.getParameter("fileType");
                String tempPSPdfFileLocation =  "";
                boolean tempIsDropShip = false;
                int cstId = -1;

                try{
                    cstId =  Integer.parseInt( cstIdStr );
                }catch(NumberFormatException e){}

                NewPackingSlipAction packingSlipAction = new NewPackingSlipAction();
                String host 			= request.getHeader ( "HOST" );
                String packingSlipFile 	= null;
                String commercialInvoiceFile = null;
                String mineType = "PDF";
                // Load the Client Information
                ClientInfo clientInfo = new ClientInfo();
                clientInfo = UserDAO.getClientAddressInfo(  );

                PackingSlipForm packingSlipForm = NewPackingSlipDAO.loadPackingSlipById (cstId);
                tempIsDropShip = packingSlipForm.isDropShippment();
                packingSlipForm.setDropShippment( false );//setting to false because the we need generating pdf of packing slip type, after pdf generation set back to original status


                if( fileType != null && fileType.trim().length() > 0 && "packingslip".equalsIgnoreCase(fileType) )
                {
                    if( "PDF".equalsIgnoreCase( mineType ) )
                    {
                        packingSlipFile = packingSlipAction.getPackingSlipAsPDFFile( host, packingSlipForm, (HashMap) session.getAttribute (SessionKeys.FINAL_INVENTORY_MAP ) ) ;
                    }
                    request.setAttribute( "PDFFileName", new File(packingSlipFile).getName() );
                }
                else
                {
                    if( "PDF".equalsIgnoreCase( mineType ) )
                    {
                        commercialInvoiceFile = CommercialInvoiceAction.getCommercialInvoiceAsPDFFile( packingSlipForm.getSalesOrderId()+"", packingSlipForm.getCustomerShippingId()+"", host, packingSlipForm.getLabel() );
                    }
                    request.setAttribute( "PDFFileName", new File(commercialInvoiceFile).getName() );
                }
                packingSlipForm.setDropShippment( tempIsDropShip );//set back to original drop ship status
                return  mapping.findForward( "generetedPDF" );
            }
            catch( Throwable t )
            {
                errors.put( "Internal Server Error", "Could not generate Packing Slip and Commercial Invoice PDF's " );
                return  mapping.findForward( "generetedPDF" );
            }
        }
        if( shippingAdviseForm != null )
        {
            request.setAttribute( "trackingNumbers", shippingAdviseForm.getTracking() );
            request.setAttribute( "pulledLotMap", shippingAdviseForm.getPulledLotMap() );
            request.setAttribute( "weightMeasurementList", NewPackingSlipDAO.loadWeightMeasurements() );
			request.setAttribute( "uomPgkDimensionList", NewPackingSlipDAO.loadUomPkgDimensionList() );
        }

        session.setAttribute( "shippingAdviseForm", shippingAdviseForm );
        if( shippingAdviseForm != null )
        {
            if ( shippingAdviseForm.getStatus() != null && shippingAdviseForm.getStatus().equals ( Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED ) )
            {
                return mapping.findForward( "cancelview" );
            }
        }
        return mapping.findForward( "success" );
    }


    private HashMap buildPulledLotMap( HttpServletRequest request )
    {
        String[] trackingNumbers = request.getParameterValues( "tracking" );
        String[] trackingIds = request.getParameterValues( "trackingId" );
        String[] cslintIds = request.getParameterValues( "id" );
        String[] lotIds = request.getParameterValues( "lotId" );

        int iLotId = -1;
        int iCslintId = -1;
        int iTrackingId = -1;

        HashMap pulledLotMap = new HashMap();
        ArrayList lotList = null;
        String trackingNumber = null;

        if( ( lotIds != null ) && ( lotIds.length > 0 ) )
        {
            for( int i=0; i<lotIds.length; i++ )
            {
                try
                {
                    iLotId = Integer.parseInt( lotIds[i] );
                    iCslintId = Integer.parseInt( cslintIds[i] );

                    if( ( trackingIds[i] != null ) && ( trackingIds[i].trim().length() != 0 ) )
                    {
                        iTrackingId = Integer.parseInt( trackingIds[i] );
                    }
                    else
                    {
                        iTrackingId = -1;
                    }

                    //System.out.println( "lotId[" + i + "] = " + lotIds[i] + ", ID[" + i + "] = " + cslintIds[i] + ", trackingId[" + i + "] = " + trackingIds[i] );
                }
                catch( NumberFormatException nfe )
                {
                    System.out.println( "Exception while building lot vs tracking numbers" );
                    nfe.printStackTrace();
                }

                if( ( iTrackingId - 1 ) >= 0 )
                {
                    trackingNumber = trackingNumbers[ iTrackingId - 1 ];

                }
                else
                {
                    trackingNumber = null;
                }

                lotList = ( ArrayList ) pulledLotMap.get( trackingNumber );
                if( lotList == null )
                {
                    lotList = new ArrayList();
                }

                lotList.add( new CustomerShippingLotNumberData( iCslintId, iLotId, trackingNumber ) );
                pulledLotMap.put( trackingNumber, lotList );

            }
        }

        return pulledLotMap;
    }



    private String getShipAlertMessageBody( String host, ShippingAdviseForm shippingAdviseForm )
    {
        StringBuffer htmlView = new StringBuffer();
        String MFG_PART_NUMBER_KEY 	= "";
        String MKT_PART_NUMBER_KEY 	= "";
        String CUSTOMER_PART_NUMBER_KEY = "";
        String CUSTOMER_LABEL_NUMBER_KEY = "";
        String WEIGHT_MEASUREMENT = "";

        try
		{
			 MFG_PART_NUMBER_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.mfgPartNumber" );
		}
		catch ( NullPointerException e )
		{
			 MFG_PART_NUMBER_KEY = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
		}
        try
		{
			 MKT_PART_NUMBER_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.mktgPartNumber" );
		}
		catch ( NullPointerException e )
		{
			 MKT_PART_NUMBER_KEY = Labels.DEFAULT_MKTG_PART_NUMBER_LABEL;
		}

        try
		{
			 CUSTOMER_PART_NUMBER_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.customerPartNumber" );
		}
		catch ( NullPointerException e )
		{
			 CUSTOMER_PART_NUMBER_KEY = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
		}

        try
		{
			 CUSTOMER_LABEL_NUMBER_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.labelNumber" );
		}
		catch ( NullPointerException e )
		{
			 CUSTOMER_LABEL_NUMBER_KEY = "Label Number";
		}
        /*try
		{
			 WEIGHT_MEASUREMENT = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.WeightMeasurements" );
		}
		catch ( NullPointerException e )
		{
			 WEIGHT_MEASUREMENT = Labels.DEFAULT_WEIGHT_MEASUREMENT_LABEL;
		}*/


        String packingSlipNumber = shippingAdviseForm.getNumber();
        if( ( packingSlipNumber == null ) || ( packingSlipNumber != null && packingSlipNumber.trim().length() == 0 ) ) { packingSlipNumber = "&nbsp;"; }

        String invoiceNumber = shippingAdviseForm.getInvoiceNumber();
        if( ( invoiceNumber == null ) || ( invoiceNumber.trim().length() == 0 ) ) { invoiceNumber = "&nbsp;"; }

        String poNumber = shippingAdviseForm.getPoNumber();
        if( ( poNumber == null ) || ( poNumber.trim().length() == 0 ) ) { poNumber = "&nbsp;"; }

        String flightNumber = shippingAdviseForm.getFlightNumber();
        if( ( flightNumber == null ) || ( flightNumber.trim().length() == 0 ) ) { flightNumber = "&nbsp;"; }

        String cartonCount = shippingAdviseForm.getCartonCount();
        if( ( cartonCount == null ) || ( cartonCount.trim().length() == 0 ) ) { cartonCount = "&nbsp;"; }

        String flightRoute = shippingAdviseForm.getFlightRoute();
        if( ( flightRoute == null ) || ( flightRoute.trim().length() == 0 ) ) { flightRoute = "&nbsp;"; }

        String uomPkgDimension = shippingAdviseForm.getUomPkgDimension();
        if( ( uomPkgDimension == null ) || ( uomPkgDimension.trim().length() == 0 ) ) { uomPkgDimension = "&nbsp;"; }

        String uomWeight = shippingAdviseForm.getWeightType();
        if( ( uomWeight == null ) || ( uomWeight.trim().length() == 0 ) ) { uomWeight = "&nbsp;"; }

        String weight = shippingAdviseForm.getWeight();
        if( ( weight == null ) || ( weight.trim().length() == 0 ) ) { weight = "&nbsp;"; }

        String grossWeight = shippingAdviseForm.getGrossWeight();
        if( ( grossWeight == null ) || ( grossWeight.trim().length() == 0 ) ) { grossWeight = "&nbsp;"; }

        String packageDimension = shippingAdviseForm.getPackageDimension();
        if( ( packageDimension == null ) || ( packageDimension.trim().length() == 0 ) ) { packageDimension = "&nbsp;"; }

        String assmCountryOfOrigin = shippingAdviseForm.getCountryOfAssyOrigin();
        if( ( assmCountryOfOrigin == null ) || ( assmCountryOfOrigin.trim().length() == 0 ) ) { assmCountryOfOrigin = "&nbsp;"; }

        String fabCountryOfOrigin = shippingAdviseForm.getCountryOfFabOrigin();
        if( ( fabCountryOfOrigin == null ) || ( fabCountryOfOrigin.trim().length() == 0 ) ) { fabCountryOfOrigin = "&nbsp;"; }

        String shippingMethod = shippingAdviseForm.getShippingMethod();
        if( ( shippingMethod == null ) || ( shippingMethod.trim().length() == 0 ) ) { shippingMethod = "&nbsp;"; }

        String deliveryTerms = shippingAdviseForm.getDeliveryTerms();
        if( ( deliveryTerms == null ) || ( deliveryTerms.trim().length() == 0 ) ) { deliveryTerms = "&nbsp;"; }

        String status = shippingAdviseForm.getStatus();
        if( ( status == null ) || ( status != null && status.trim().length() == 0 ) ) { status = "&nbsp;"; }

        String noOfPalettes = shippingAdviseForm.getPaletteCount();
        if( ( noOfPalettes == null ) || ( noOfPalettes != null && noOfPalettes.trim().length() == 0 ) ) { noOfPalettes = "&nbsp;"; }

        String packedby = shippingAdviseForm.getPackedby();
        if( ( packedby == null ) || ( packedby != null && packedby.trim().length() == 0 ) ) { packedby = "&nbsp;"; }

        String title = shippingAdviseForm.getTitle();
        if( ( title == null ) || ( title != null && title.trim().length() == 0 ) ) { title = "&nbsp;"; }

        String shippingInstructions = shippingAdviseForm.getShippingInstructions();
        if( ( shippingInstructions == null ) || ( shippingInstructions != null && shippingInstructions.trim().length() == 0 ) ) { shippingInstructions = "&nbsp;"; }

        String comments = shippingAdviseForm.getComments();
        if( ( comments == null ) || ( comments != null && comments.trim().length() == 0 ) ) { comments = "&nbsp;"; }

        String actualShipDate = shippingAdviseForm.getShipDate();
        if( ( actualShipDate == null ) || ( actualShipDate != null && actualShipDate.trim().length() == 0 ) ) { actualShipDate = "&nbsp;"; }

        String freightInstructions = shippingAdviseForm.getFreightInstructions();
        if( ( freightInstructions == null ) || ( freightInstructions != null && freightInstructions.trim().length() == 0 ) ) { freightInstructions = "&nbsp;"; }

        String letterOfCreditNo = shippingAdviseForm.getLetterOfCreditNo();
        if( ( letterOfCreditNo == null ) || ( letterOfCreditNo != null && letterOfCreditNo.trim().length() == 0 ) ) { letterOfCreditNo = "&nbsp;"; }

        String mawbNo = shippingAdviseForm.getMawb();
        if( ( mawbNo == null ) || ( mawbNo != null && mawbNo.trim().length() == 0 ) ) { mawbNo = "&nbsp;"; }

        String hawbNo = shippingAdviseForm.getHawb();
        if( ( hawbNo == null ) || ( hawbNo != null && hawbNo.trim().length() == 0 ) ) { hawbNo = "&nbsp;"; }

        String flightNoOne = shippingAdviseForm.getFlightNumberOne();
        if( ( flightNoOne == null ) || ( flightNoOne != null && flightNoOne.trim().length() == 0 ) ) { flightNoOne = "&nbsp;"; }

        String flightNoTwo = shippingAdviseForm.getFlightNumberTwo();
        if( ( flightNoTwo == null ) || ( flightNoTwo != null && flightNoTwo.trim().length() == 0 ) ) { flightNoTwo = "&nbsp;"; }

        String etd = shippingAdviseForm.getEtd();
        if( ( etd == null ) || ( etd != null && etd.trim().length() == 0 ) ) { etd = "&nbsp;"; }

        String eta = shippingAdviseForm.getEta();
        if( ( eta == null ) || ( eta != null && eta.trim().length() == 0 ) ) { eta = "&nbsp;"; }

        String[] trackingNo = shippingAdviseForm.getTracking();

        String vendorNumberLabel = null;
        try
		{
            vendorNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.packingSlip.VendorFace.InvoiceNumber" );
            if ( vendorNumberLabel == null )
            {
                vendorNumberLabel = Labels.DEFAULT_VENDOR_NUMBER_LABEL;
            }
        }
        catch ( NullPointerException e )
		{
			 vendorNumberLabel = Labels.DEFAULT_VENDOR_NUMBER_LABEL;
		}

        htmlView.append( "<HTML><HEAD><TITLE>Scalar Soft - ChipTrac</TITLE><META http-equiv=Content-Type content='text/html; charset=windows-1252'></HEAD><style>.NArialL{ COLOR: #000000;font-family: verdana;font-size: 8pt;font-weight:bold}.NArialRS{COLOR: #000000;FONT-FAMILY: verdana;FONT-SIZE: 7pt;}</style>");
        htmlView.append( "<BODY><table bgcolor='#FFFFF0' border='1' width='800' cellspacing=1 bordercolor='#CCCCFF' align=center valign=top class='NArialL'>" );
        htmlView.append( "<tr><td><table border='0' width='98%' cellspacing=5 bordercolor='#CCCCFF' align=center valign=top class='NArialL'><tr><td colspan=5><br></td></tr><tr height=5>" );
        htmlView.append( "<td><img src='http://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/images/scalar_logo.jpg' alt='LOGO' height='72' width='180'></td><td colspan=3 align=center><font size=5><b><u>Shipment Notification</u></b></font><br><br></td><td>&nbsp;</td></tr>");
        htmlView.append( "<tr height=2><td bgcolor='#993333' colspan=2>&nbsp;</td><td width='10%'></td><td bgcolor='#993333' colspan=2>&nbsp;</td></tr>" );
        htmlView.append( "<tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;");
        htmlView.append( vendorNumberLabel );
        htmlView.append( ":</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( packingSlipNumber );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;PO Number:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( poNumber );
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Actual Ship Date: (mm/dd/yyyy)</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( actualShipDate );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;No. Of Boxes:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( cartonCount );
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Shipping Instructions:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( shippingInstructions );
        if( ConfigManager.getShowPackageDimensionInPackingSlip() )
        {
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Net Weight:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        }
        else
        {
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Weight:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );    
        }
        htmlView.append( weight + "&nbsp;" + uomWeight );
        if( ConfigManager.getShowPackageDimensionInPackingSlip() )
        {
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Package Dimension:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( packageDimension + "&nbsp;" + uomPkgDimension );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Gross Weight:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( grossWeight + "&nbsp;" + uomWeight );
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Country of Origin(Fab):</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( fabCountryOfOrigin );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Country of Origin(Assy):</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( assmCountryOfOrigin );
        }
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Packed By:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( packedby );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Forwarder:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( shippingMethod );
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Title:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( title );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Delivery Terms:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( deliveryTerms );
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Freight Instructions:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( freightInstructions );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Number of Pallets:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( noOfPalettes );
        if( ConfigManager.getShowPackageDimensionInPackingSlip() )
        {
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;MAWB No:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( mawbNo );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;HAWB No:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( hawbNo );
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Flight-1 No:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( flightNoOne );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Flight-2 No:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( flightNoTwo );
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;ETD:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( etd );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;ETA:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( eta );
        }
        htmlView.append( "</td></tr><tr><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Freight Tracking No:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append ( "<table class='NArialRS'>" );
        if( trackingNo != null && trackingNo.length > 0 )
        {
            for(int i = 0 ; i < trackingNo.length ; i++ )
            {
                htmlView.append( "<tr><td class='NArialL' >" + trackingNo[i] + "</td></tr>" );
            }
        }
        else
        {
             htmlView.append( "<tr><td>&nbsp;</td></tr>" );
        }
        htmlView.append ( "</table>" );
        htmlView.append( "</td><td width='10%' NOWRAP>&nbsp;</td><td width='15%' align='left' bgcolor='#DEE1E2' bgcolor='#DEE1E2' NOWRAP>&nbsp;&nbsp;Comments:</td><td width='30%' align='left' bgcolor='#DEE1E2' NOWRAP>" );
        htmlView.append( comments );
        htmlView.append( "</td></tr>" );

        ClientInfo clientInfo = null;
        try{
            clientInfo = UserDAO.getClientAddressInfo();
        } catch(Exception e) {};

        htmlView.append ( "<tr><td>&nbsp;</td></tr>" );
        /* LINE ITEM DETAILS*/
        if( shippingAdviseForm.isDropShippment() == true )
        {
            htmlView.append( "<tr><td colspan=5>" );
            htmlView.append( "<table border='0' width='100%' bordercolor='#FFFFFF'><tr>" );
            htmlView.append( "<td width='4%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Line Item</font></td>" );
            htmlView.append( "<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>"+ MKT_PART_NUMBER_KEY +"</font></td>" );
            htmlView.append( "<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>"+ MFG_PART_NUMBER_KEY +"</font></td>" );
            htmlView.append( "<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Shipped "+ MFG_PART_NUMBER_KEY +"</font></td>" );
            htmlView.append( "<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>" + CUSTOMER_PART_NUMBER_KEY + "</font></td>" );
            htmlView.append( "<td width='30%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Description</font></td>" );
            htmlView.append( "<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Unit Type</font></td>" );
            htmlView.append( "<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Req. Dock Date</font></td>" );
            htmlView.append( "<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Sch. Ship Date</font></td>" );
            htmlView.append( "<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Quantity To be Shipped</font></td>" );
            htmlView.append( "<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Quantity Shipped</font></td>" );
            htmlView.append( "<td width='8%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Status</font></td></tr>" );
            CustomerShippingLineItems csLineItem = null;
            ArrayList lineItems = shippingAdviseForm.getLineitems();
			int lineItemCount 	= lineItems.size();
            String shippedSKU = null;

            for( int i = 0 ; i < lineItemCount ; i++ )
            {

                csLineItem = ( CustomerShippingLineItems ) lineItems.get (i);

                String lineItemNoStr           = "";
                int lineItemNo              = csLineItem.getLineitemNumber();
                if(  lineItemNo == 0 )
                    lineItemNoStr = "&nbsp;";
                else
                    lineItemNoStr = lineItemNo + "";


                String partNumber           = csLineItem.getPart_Number();
                if( ( partNumber == null ) || ( partNumber != null && partNumber.trim().length() == 0 ) ) { partNumber = "&nbsp;"; }
                String mktpartNumber           = csLineItem.getMkt_Part_Number();
                if( ( mktpartNumber == null ) || ( mktpartNumber != null && mktpartNumber.trim().length() == 0 ) ) { mktpartNumber = "&nbsp;"; }

                String customerPartNumber 	= csLineItem.getCustomer_Part_Number();
                if( ( customerPartNumber == null ) || ( customerPartNumber != null && customerPartNumber.trim().length() == 0 ) ) { customerPartNumber = "&nbsp;"; }

                String customerLabelNumber 	= csLineItem.getCustomer_Label_Number();
                if( ( customerLabelNumber == null ) || ( customerLabelNumber != null && customerLabelNumber.trim().length() == 0 ) ) { customerLabelNumber = "&nbsp;"; }

                String description 			= csLineItem.getCool_Description()  ;
                if( ( description == null ) || ( description != null && description.trim().length() == 0 ) ) { description = "&nbsp;"; }

                String units 				= ( csLineItem.getUnits() == null ? "" : csLineItem.getUnits() );
                if( ( units == null ) || ( units != null && units.trim().length() == 0 ) ) { units = "&nbsp;"; }

                String requestedDate        = csLineItem.getCool_Requested_Date();
                if( ( requestedDate == null ) || ( requestedDate != null && requestedDate.trim().length() == 0 ) ) { requestedDate = "&nbsp;"; }

                String scheduleDate  ;//       = csLineItem.getCool_Schedule_Date();
                //if( ( scheduleDate == null ) || ( scheduleDate != null && scheduleDate.trim().length() == 0 ) ) { scheduleDate = "&nbsp;"; }
                if ( csLineItem.getCool_Revised_Date() != null && csLineItem.getCool_Revised_Date().trim().length()>0)
                {
            	    scheduleDate = csLineItem.getCool_Revised_Date();
                }
                else if ( csLineItem.getCool_Schedule_Date() != null && csLineItem.getCool_Schedule_Date().trim().length()>0)
                {
                	scheduleDate = csLineItem.getCool_Schedule_Date();
                }
                else
                {
                	scheduleDate =  "&nbsp;";
                }

                String qtyToShipStr              = "";
                String qtyPulledStr            = "";
                int    qtyToShip              = csLineItem.getQtyToShip();
                int    qtyPulled            = csLineItem.getQtyPulled();

                if(  qtyToShip == 0 )
                    qtyToShipStr = "&nbsp;";
                else
                    qtyToShipStr = qtyToShip + "";

                if( qtyPulled == 0 )
                    qtyPulledStr = "&nbsp;";
                else
                    qtyPulledStr = qtyPulled + "";

                htmlView.append( "<tr bgcolor='#DEE1E2'>" );
                htmlView.append( "<td width='4%'  align='center' class='NArialL'>" + lineItemNoStr + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + mktpartNumber + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + partNumber + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" );
                htmlView.append ("<table border='0' width='100%'>");
                String[] shippedSKUList = csLineItem.getShipped_Part_Number();
                if( shippedSKUList != null )
                {
                    for ( int v = 0; v < shippedSKUList.length; v++ )
                    {
                        shippedSKU = shippedSKUList[v];
                        if( shippedSKU != null && shippedSKU.trim().length() > 0 && ! csLineItem.getPart_Number().equalsIgnoreCase( shippedSKU )  )
                        {
                            htmlView.append ( "<tr><td align='left' valign='middle' class='NArialL'>" + shippedSKU + "</td></tr>");
                        }
                        shippedSKU = "";
                    }
                }
                htmlView.append ( "</table></td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + customerPartNumber + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + description + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + units + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + requestedDate + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + scheduleDate + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + qtyToShipStr + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + qtyPulledStr + "</td>" );
                htmlView.append( "<td width='15%' align='center' class='NArialL'>" + status + "</td>" );
                htmlView.append( "</tr>");

            }
            htmlView.append( "</table></td></tr>" );
        }

        /*ArrayList lotList = null;
        CustomerShippingLotNumberData pulledLot = null;
        HashMap pulledLotMap = shippingAdviseForm.getPulledLotMap();
        String trackingNumbers[] = shippingAdviseForm.getTracking();
        htmlView.append( "<tr><td colspan='5'><table class='NArialL' cellspacing=3 cellpadding=0 width='50%' border=0>" );
        if( trackingNumbers != null )
        {
            ////////// LIST TRACKING NUMBERS AND CORRESPONDING LOT NUMBERS ///////////

            for( int i=0; i<trackingNumbers.length; i++)
            {
                if( ( trackingNumbers[i] != null ) && ( trackingNumbers[i].trim().length() != 0 ) )
                {
                    htmlView.append( "<tr><td width='25%' bgcolor='#993333' NOWRAP>&nbsp;&nbsp;<font color='#FFFFFF'>Freight Tracking #:</font></td><td width='50%' bgcolor='#DEE1E2' NOWRAP>" );
                    htmlView.append( trackingNumbers[i] + "</td></tr>" );

                    if( ( pulledLotMap != null ) && ( pulledLotMap.isEmpty() == false ) )
                    {
                        lotList = ( ArrayList ) pulledLotMap.get( trackingNumbers[i] );
                        if( ( lotList != null ) && ( lotList.isEmpty() == false ) )
                        {
                            int size = lotList.size();
                            for( int j=0; j<size; j++ )
                            {
                                pulledLot = ( CustomerShippingLotNumberData ) lotList.get( j );
                                if( pulledLot != null )
                                {
                                    htmlView.append( "<tr height=20>" );
                                    htmlView.append( "<td width='25%' align=center bgcolor='#DEE1E2' NOWRAP><font color='#993333'>Lot, Qty:</font></td>" );
                                    htmlView.append( "<td width='50%' align=left   bgcolor='#DEE1E2' NOWRAP>" );
                                    htmlView.append( pulledLot.getLotNumber() + "&nbsp;&nbsp;&nbsp;&rarr;&nbsp;&nbsp;&nbsp;" );
                                    htmlView.append( pulledLot.getQtyPullAsString() + "</td></tr>" );
                                }
                            }

                            htmlView.append( "<tr><td colspan=2><br></td></tr>" );
                        }
                    }
                }
            }
        }

        ////////// LIST LOT NUMBERS WITH NO TRACKING NUMBER ///////////

        if( ( pulledLotMap != null ) && ( pulledLotMap.isEmpty() == false ) )
        {
            lotList = ( ArrayList ) pulledLotMap.get( null );
            if( ( lotList != null ) && ( lotList.isEmpty() == false ) )
            {
                htmlView.append( "<tr><td colspan='5'><br><table class='NArialL' cellspacing=3 cellpadding=0 width='60%' border=0>" );
                htmlView.append( "<tr><td colspan=2 bgcolor='#993333' NOWRAP><font color='#FFFFFF'>" );
                htmlView.append( "Lots with out Tracking Numbers:</font></td></tr>" );

                int size = lotList.size();
                for( int i=0; i<size; i++ )
                {
                    pulledLot = ( CustomerShippingLotNumberData ) lotList.get( i );
                    if( pulledLot != null )
                    {
                        htmlView.append( "<tr height=20>" );
                        htmlView.append( "<td width='25%' align=center bgcolor='#DEE1E2' NOWRAP><font color='#993333'>Lot, Qty:</font></td>" );
                        htmlView.append( "<td width='50%' align=left   bgcolor='#DEE1E2' NOWRAP>" );
                        htmlView.append( pulledLot.getLotNumber() + "&nbsp;&nbsp;&nbsp;&rarr;&nbsp;&nbsp;&nbsp;" );
                        htmlView.append( pulledLot.getQtyPullAsString() + "</td></tr>" );
                    }
                }

                htmlView.append( "<tr><td colspan=2><br></td></tr>" );
            }
        }


        htmlView.append( "</table></td></tr>" );  */

        htmlView.append( "<tr><td colspan=5><br><br><br><table border=0 cellspacing=0 cellpadding=0 width=60% align=left>" );
        htmlView.append( "<font size=-2>&nbsp;</font></table></td></tr></table><br></td></tr></table></BODY></HTML>" );

        return htmlView.toString();
    }

    private HashMap getFinalInventoryMapByCustomerShippingId( HashMap finalInventoryMap )
    {
        HashMap finalInventoryMapByCustomerShippingId = new HashMap();
        ArrayList dataList = null;
        FinalInventoryData inventoryData = null;
        Iterator it = finalInventoryMap.keySet().iterator();
        while ( it.hasNext() )
        {
			dataList = (ArrayList)finalInventoryMap.get( it.next() );

			if ( dataList.size() >= 1 )
			{
				inventoryData 	= (FinalInventoryData)dataList.get( 0 );
				finalInventoryMapByCustomerShippingId.put( inventoryData.getCsLineItemId()+"", dataList );
			}
        }

		return finalInventoryMapByCustomerShippingId;
    }

    private HashMap loadNewFinalInventoryDataListMap ( HashMap existingFinalInventoryDataListMap , HashMap dbFinalInventoryDataListMap )
    {
    	ArrayList existingInventoryDataList = null;
        String lineItemId                   = null;
        HashMap inventoryDataListMap        = new HashMap();

    	if( dbFinalInventoryDataListMap != null && dbFinalInventoryDataListMap.isEmpty() == false )
    	{
            Iterator it = dbFinalInventoryDataListMap.keySet().iterator();

			while( it.hasNext() )
			{
				lineItemId	= (String) it.next() ;
                existingInventoryDataList = ( ArrayList ) existingFinalInventoryDataListMap.get( lineItemId );

                if( existingInventoryDataList != null && existingInventoryDataList.isEmpty() == false )
			    {
                    existingFinalInventoryDataListMap.put( lineItemId , existingInventoryDataList  );
                }
                else
                {
                    existingFinalInventoryDataListMap.put( lineItemId , dbFinalInventoryDataListMap.get( lineItemId )  );
                }
            }
    	}

        return existingFinalInventoryDataListMap;
    }

    private ArrayList loadShippedPartNoFromInventoryDataList ( HashMap finalInventoryDataListMap , int lineItemId )
    {
    	ArrayList inventoryDataList     = null;
        ArrayList shippedPartNoList     = new ArrayList();
        FinalInventoryData  finalInventoryData  = null;

    	if( finalInventoryDataListMap != null && finalInventoryDataListMap.isEmpty() == false )
    	{
            inventoryDataList = ( ArrayList ) finalInventoryDataListMap.get( lineItemId + "" );
            for ( int i = 0; i < inventoryDataList.size() ; i++ )
            {
                finalInventoryData = ( FinalInventoryData ) inventoryDataList.get(i);
                if( finalInventoryData != null && finalInventoryData.getQuantityPull() > 0 )
                {
                    shippedPartNoList.add( finalInventoryData.getMktPartNumber() );
                }
            }
    	}

        return shippedPartNoList;
    }
    public static boolean sendShipmentNotificationMail ( ActionMapping mapping, HttpServletRequest request, HttpServletResponse response, String messageBody, int customerShippingId, String psLabel ) throws Exception
    {
        boolean mailSuccess = true;
        String[] clientShipAlertEmails = NewPackingSlipDAO.loadClientEmailsForShipAlert();
        String[] allShipAlertEmails    = NewPackingSlipDAO.loadAllShipAlertEmails( customerShippingId );
        SendMailForm sendMailForm = new SendMailForm();
        sendMailForm.setRecipientType("customer");//setting to customer beacause pdf attachment shoule be of ps type
        sendMailForm.setAttachMIMEType( "PDF" );
        sendMailForm.setSendCommercialInvoice( "on" );
        sendMailForm.setSubject( "Shipment Notification - " + psLabel + ", " + new Date( System.currentTimeMillis() ) );
        //if( clientShipAlertEmails != null && clientShipAlertEmails.length > 0 )
        //{
          //  sendMailForm.setToUsers( clientShipAlertEmails );
        //}
        //else if ( ( clientShipAlertEmails == null || clientShipAlertEmails.length == 0 ) && allShipAlertEmails != null && allShipAlertEmails.length > 0   )
        //{
        sendMailForm.setToUsers( allShipAlertEmails );
        //}
        //sendMailForm.setCcUsers( allShipAlertEmails );

        request.setAttribute( "customerShippingId", customerShippingId+"" );
        request.setAttribute( "action", "save" );
        request.setAttribute( "isFromTrackingNoPage", "true" );
        request.setAttribute( "shipAlertMessage", messageBody );
        new SendMailAction().execute( mapping, sendMailForm, request, response );
        mailSuccess = false;

        HashMap sendMailInfo = ( HashMap ) request.getAttribute( SessionKeys.INFO_MESSAGES) ;
        HashMap sendMailError = ( HashMap ) request.getAttribute( SessionKeys.ERROR_MESSAGES) ;
        if( sendMailInfo.containsKey( "Packingslip and Commercial Invoices have been sent, successfully" ) )
        {
            mailSuccess = true;
            sendMailInfo.remove( "Packingslip and Commercial Invoices have been sent, successfully" );
            //sendMailInfo.put ( "Information has been updated successfully and also sent mail", null );
        }
        else
        {
            mailSuccess = false;
            sendMailError.remove("Sending Failed ");
            //sendMailInfo.put ( "Information has been updated successfully and could not send mail", null );
        }
        return mailSuccess;
    }
}

